﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Microsoft.Phone.Info;
using DailyBread.DataServiceReference;
using System.Data.Services.Client;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Xml;
using System.Reflection;

namespace DailyBread
{
    public class Util
    {
        private static DailyBreadDataServiceContext commentContext = null, favContext = null, logContext = null;

        //Replace the host server and port number with the values
        // for the test server that is hosting your data service instance.
        //private static Uri svcUri = new Uri("http://83235b60ea9c4592bda831642e0796f3.cloudapp.net/DailyBreadDataService.svc");
        private static Uri svcUri = new Uri("http://dailybreadprod.cloudapp.net/DailyBreadDataService.svc");
        private const string httpPrefix = "http://mobi.rbc.org/odb/";

        static Util()
        {
            commentContext = new DailyBreadDataServiceContext(svcUri);
            favContext = new DailyBreadDataServiceContext(svcUri);
            logContext = new DailyBreadDataServiceContext(svcUri);
        }

        public static string GetPhoneOSAppInfo()
        {
            System.OperatingSystem osInfo = System.Environment.OSVersion;

            string modelname = null;
            object modelobject = null;
            if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceName", out modelobject))
                modelname = modelobject as string;
            string ManufacturerName = "";
            object manufacturerobject;
            if (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out manufacturerobject))
                ManufacturerName = manufacturerobject.ToString();

            var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);

            string version = versionAttrib.Version.ToString();

            return ManufacturerName + ' ' + modelname + ", " + osInfo.Version.ToString() + ", app:" + version;
        }

        public static Uri GetNavUrl(DateTime date)
        {
            StringBuilder urlToNavigate = new StringBuilder(date.Year.ToString(), 20);
            urlToNavigate.Append('-');
            if (date.Month < 10)
                urlToNavigate.Append('0');
            urlToNavigate.Append(date.Month);
            urlToNavigate.Append('-');
            if (date.Day < 10)
                urlToNavigate.Append('0');
            urlToNavigate.Append(date.Day);
            urlToNavigate.Insert(0, httpPrefix);
            urlToNavigate.Append(".html");
            Uri uri = new Uri(urlToNavigate.ToString(), UriKind.Absolute);
            return uri;
        }

        public static string GetShortNavUrl(DateTime date)
        {
            StringBuilder urlToNavigate = new StringBuilder(date.Year.ToString(), 20);
            urlToNavigate.Append('-');
            if (date.Month < 10)
                urlToNavigate.Append('0');
            urlToNavigate.Append(date.Month);
            urlToNavigate.Append('-');
            if (date.Day < 10)
                urlToNavigate.Append('0');
            urlToNavigate.Append(date.Day);
            return urlToNavigate.ToString();
        }

        public static string GetUserId()
        {
            string userId;

            // get userid
            string anid = UserExtendedProperties.GetValue("ANID") as string;
            if (anid == null)
            {
                string deviceId = DeviceExtendedProperties.GetValue("DeviceUniqueId") as string;
                if (deviceId == null)
                    userId = "public";
                else
                    userId = deviceId;
            }
            else
            {
                userId = anid.Substring(2, 32);
            }

            return userId;
        }

        #region Logs operation
        // store log entry into cache
        public static void AddToLog(string action)
        {
            LogCollection storedLog = IsolatedStorageHelper.GetObject<LogCollection>("Log");
            if (storedLog == null)
            {
                storedLog = new LogCollection();
                storedLog.LogList = new Collection<DailyBreadLogs>();
            }

            DailyBreadLogs newLog = new DailyBreadLogs();
            DateTime actionTime = System.DateTime.UtcNow;
            newLog.ActionTime = actionTime.ToString("yyyy/MM/dd HH:mm:ss.ffff");
            newLog.PartitionKey = actionTime.ToString("yyyyMMdd"); // use day of the year as partition key so that we can query per day data
            newLog.RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - actionTime.Ticks, Guid.NewGuid());
            newLog.UserId = GetUserId();
            newLog.UserAction = action;
            storedLog.LogList.Add(newLog);
            IsolatedStorageHelper.SaveObject("Log", storedLog);
        }

        // retrieve log from cache and send to server
        public static void UploadLogToAzure()
        {

            LogCollection storedLog = IsolatedStorageHelper.GetObject<LogCollection>("Log");
            if (storedLog == null || storedLog.LogList == null)
                return;

            foreach (DailyBreadLogs log in storedLog.LogList)
            {
                logContext.AddToLogs(log);
            }

            logContext.BeginSaveChanges(SaveChangesOptions.Batch, result =>
            {
                try
                {
                    var response = logContext.EndSaveChanges(result);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException.Message);
                }
                finally
                {
                    // delete the cache anyway even with error 
                    // so that we'll always recover from it
                    IsolatedStorageHelper.DeleteObject("Log");
                }
            },
            null
            );
        }
        #endregion

        #region Comments operation
        public static void GetCommentsFromAzure(DateTime currentDisplayDate, 
                                                Action<IEnumerable<DailyBreadComments>> GetCommentsCallback,
                                                Action<Exception> OnError)
        {
            // only retrieve this daily bread's comments from server
            string filter =HttpUtility.UrlEncode("BreadUrl eq '" + Util.GetShortNavUrl(currentDisplayDate) + "'");
            DataServiceQuery<DailyBreadComments> todayComments = commentContext.Comments.AddQueryOption("$filter", filter)
                                                                .AddQueryOption("rand", Guid.NewGuid().ToString()); // to avoid IE client cache
                                                                 
            todayComments.BeginExecute(result =>
                {
                    try
                    {
                        
                        var comment = todayComments.EndExecute(result);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            GetCommentsCallback(comment);
                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            OnError(ex);
                        });
                    }

                }, 
                null);
        }

        public static void SaveCommentToAzure(DateTime currentDisplayDate, 
                                              DailyBreadComments comment, 
                                              Action<DailyBreadComments> SaveCommentCallback = null,
                                              Action<Exception> onError = null)
        {

            commentContext.AddToComments(comment);
            commentContext.BeginSaveChanges(result =>
                {
                    try
                    {
                        var response = commentContext.EndSaveChanges(result);
                        Deployment.Current.Dispatcher.BeginInvoke(() => { SaveCommentCallback(comment); });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            onError(ex);
                        });
                    }
                },
                comment
            );
        }

        public static void RemoveComment(DailyBreadComments comment,
                                         Action<DailyBreadComments> DeleteCommentCallback,
                                         Action<Exception> onError)
        {
            commentContext.DeleteObject(comment);
            commentContext.BeginSaveChanges(result =>
            {
                try
                {
                    commentContext.EndSaveChanges(result);
                    Deployment.Current.Dispatcher.BeginInvoke(() => { DeleteCommentCallback(comment); });
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        onError(ex);
                    });
                }
            }, null); 



        }
        #endregion

        #region Amen operations
        public static void SaveFavToAzure(AppContext context)
        {

            // only retrieve this daily bread's favs from server
            string filter = "BreadDate eq '" + Util.GetShortNavUrl(context.currentDisplayDate) + "'";
            DataServiceQuery<DailyBreadFavorites> todayFavorites = favContext.Favorites.AddQueryOption("$filter", filter);
            todayFavorites.BeginExecute(result =>
            {
                try
                {

                    List<DailyBreadFavorites> favorites = todayFavorites.EndExecute(result).ToList();

                    if (favorites.Count > 0)
                    { // exist, just update the count
                        DailyBreadFavorites fav = favorites.First();
                        fav.Count++;
                        favContext.UpdateObject(fav); 
                        favContext.BeginSaveChanges(updateresult =>
                            {
                                try
                                {
                                    var response = favContext.EndSaveChanges(updateresult);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex.InnerException.Message);
                                }
                            },
                            fav
                            );
                    }
                    else
                    {
                        DailyBreadFavorites fav = new DailyBreadFavorites();
                        DateTime favTime = DateTime.UtcNow;
                        fav.PartitionKey = favTime.ToString("yyyy");
                        fav.RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - favTime.Ticks, Guid.NewGuid());
                        fav.BreadDate = Util.GetShortNavUrl(context.currentDisplayDate);
                        fav.BreadContent = context.BreadContent;
                        fav.VerseContent = context.VerseContent;
                        fav.Count = 1;
                        context.Favorite = fav;
                        favContext.AddToFavorites(fav);
                        favContext.BeginSaveChanges(addresult =>
                            {
                                try
                                {
                                    var response = favContext.EndSaveChanges(addresult);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex.InnerException.Message);
                                }
                            },
                            fav
                        );
                    } // end of if/else
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException.Message);
                }
            }, 
            null);
        }

        public static void GetFavCountFromAzure(DateTime breadDate,
                                               Action<IEnumerable<DailyBreadFavorites>> GetFavCallback,
                                               Action<Exception> onError)
        {

            // only retrieve this daily bread's favs from server
            string filter = "BreadDate eq '" + Util.GetShortNavUrl(breadDate) +"'";
            DataServiceQuery<DailyBreadFavorites> todayFavorites = favContext.Favorites.AddQueryOption("$filter", filter);

            todayFavorites.BeginExecute(result =>
                {
                    try
                    {

                        var favorites = todayFavorites.EndExecute(result);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            GetFavCallback(favorites);

                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            onError(ex);
                        });
                    }

                },
                null);
      
        }

        public static void RemoveFavFromAzure(DateTime breadDate)
        {
            // only retrieve this daily bread's favs from server
            string filter = "BreadDate eq '" + Util.GetShortNavUrl(breadDate) + "'";
            DataServiceQuery<DailyBreadFavorites> todayFavorites = favContext.Favorites.AddQueryOption("$filter", filter);
            todayFavorites.BeginExecute(result =>
            {
                try
                {

                    List<DailyBreadFavorites> favorites = todayFavorites.EndExecute(result).ToList();

                    if (favorites.Count > 0)
                    { // found it, now decrement the count
                        DailyBreadFavorites fav = favorites.First();
                        fav.Count--;
                        favContext.UpdateObject(fav);
                        favContext.BeginSaveChanges(delresult =>
                        {
                            try
                            {
                                favContext.EndSaveChanges(delresult);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.InnerException.Message);
                            }
                        }, null); 
                    }
                    else
                    {
                        throw new KeyNotFoundException();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException.Message);
                }

            },
            null);
        }

        public static DailyVerse FindAmen(DateTime breadDate)
        {
            AmenCollection storedAmen = IsolatedStorageHelper.GetObject<AmenCollection>("Amen");
            if (storedAmen != null)
            {
                foreach (DailyVerse dv in storedAmen.verseList)
                {
                    if (dv.breadDate == breadDate)
                        return dv; 
                }
            }
            return null;
        }

        public static void RecordAmen(AppContext context, bool fav)
        {
            AmenCollection storedAmen = IsolatedStorageHelper.GetObject<AmenCollection>("Amen");
            if (storedAmen != null)
            {
                foreach (DailyVerse dv in storedAmen.verseList)
                {
                    // cached in the past
                    if (dv.verseName == context.VerseName)
                    {
                        if (dv.verseContent == null) // didn't cache the content, proceed to fill in the cache
                        {
                            dv.breadContent = context.BreadContent;
                            dv.verseContent = context.VerseContent;
                            dv.articleVerse = context.ArticleVerse;
                        }

                        // mark as personal favorite if it's cached already
                        dv.personalFav = true;
                        IsolatedStorageHelper.SaveObject("Amen", storedAmen);

                        // cached in the past, now needs to update the favorite count on server
                        SaveFavToAzure(context);

                        return;
                    }
                }
            }

            // it's not cached before.  If it's a personal fav or within last 3 days, save it
            if (fav || (System.DateTime.Today - context.currentDisplayDate).Days < 3)
            {
                if (storedAmen == null)
                {
                    storedAmen = new AmenCollection();
                    storedAmen.verseList = new ObservableCollection<DailyVerse>();
                }
                DailyVerse newVerse = new DailyVerse(context.VerseName,
                                                        context.BreadName,
                                                        context.currentDisplayDate,
                                                        context.BreadContent,
                                                        context.VerseContent,
                                                        context.ArticleVerse,
                                                        fav);

                storedAmen.verseList.Add(newVerse);
                IsolatedStorageHelper.SaveObject("Amen", storedAmen);

                if (fav)
                    SaveFavToAzure(context);
            }

            // if we are caching a new item, remove cached bread from 3 days ago
            if (!fav)
            {
                DateTime dvDate = System.DateTime.Today.AddDays(-3);
                 foreach (DailyVerse dv in storedAmen.verseList)
                 {
                     if (dv.breadDate == dvDate && !dv.personalFav)
                     {
                         storedAmen.verseList.Remove(dv);
                         IsolatedStorageHelper.SaveObject("Amen", storedAmen);
                         return;
                     }
                 }
            }
        }

        public static void RemoveAmen(DailyVerse dv)
        {
            AmenCollection savedAmen = IsolatedStorageHelper.GetObject<AmenCollection>("Amen");

            RemoveFavFromAzure(dv.breadDate);

            foreach (DailyVerse verse in savedAmen.verseList)
            {
                if (dv.breadDate == verse.breadDate)
                {
                    if ((System.DateTime.Today - dv.breadDate).Days > 3)
                    {  // if it's more than 3 days old, remove it from cache
                        savedAmen.verseList.Remove(verse);
                    }
                    else
                    { // keep it in the cache, but remove the fav flag
                        verse.personalFav = false;
                    }
                    IsolatedStorageHelper.SaveObject("Amen", savedAmen);
                }
            }

        }
        #endregion

        #region html manipulation
        public static string ConvertExtendedASCII(string HTML)
        {
            string retVal = "";
            char[] s = HTML.ToCharArray();

            foreach (char c in s)
            {
                if (Convert.ToInt32(c) > 127)
                    retVal += "&#" + Convert.ToInt32(c) + ";";
                else
                    retVal += c;
            }

            return retVal;
        }

        public static string StripHTML(string source)
        {
            try
            {
                string result;

                // Remove HTML Development formatting
                // Replace line breaks with space
                // because browsers inserts space
                result = source.Replace("\r", " ");
                // Replace line breaks with space
                // because browsers inserts space
                result = result.Replace("\n", " ");
                // Remove step-formatting
                result = result.Replace("\t", string.Empty);
                // Remove repeating spaces because browsers ignore them
                result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                      @"( )+", " ");

                // Remove the header (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*head([^>])*>", "<head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*head( )*>)", "</head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<head>).*(</head>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);


                // remove all scripts (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*script([^>])*>", "<script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*script( )*>)", "</script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //result = System.Text.RegularExpressions.Regex.Replace(result,
                //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
                //         string.Empty,
                //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<script>).*(</script>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all styles (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*style([^>])*>", "<style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*style( )*>)", "</style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<style>).*(</style>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*td([^>])*>", "\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<br />", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*li( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*div([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*tr([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*p([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,
                // comments etc - anything that's enclosed inside < >
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<[^>]*>", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @" ", " ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&bull;", " * ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lsaquo;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&rsaquo;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&trade;", "(tm)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&frasl;", "/",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lt;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&gt;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&copy;", "(c)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&reg;", "(r)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove all others. More can be added, see
                // http://hotwired.lycos.com/webmonkey/reference/special_characters/
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&(.{2,6});", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // for testing
                //System.Text.RegularExpressions.Regex.Replace(result,
                //       this.txtRegex.Text,string.Empty,
                //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // make line breaking consistent
                result = result.Replace("\n", "\r");

                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4.
                // Prepare first to remove any whitespaces in between
                // the escaped characters and remove redundant tabs in between line breaks
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\t)", "\t\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\r)", "\t\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\t)", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove multiple tabs following a line break with just one tab
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Initial replacement target string for line breaks
                //string breaks = "\r\r\r";
                //// Initial replacement target string for tabs
                //string tabs = "\t\t\t\t\t";
                //for (int index = 0; index < result.Length; index++)
                //{
                //    result = result.Replace(breaks, "\r\r");
                //    result = result.Replace(tabs, "\t\t\t\t");
                //    breaks = breaks + "\r";
                //    tabs = tabs + "\t";
                //}

                // strip leading spaces
                result = System.Text.RegularExpressions.Regex.Replace(result,
                            @"^\s+", String.Empty,
                            System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // That's it.
                return result;
            }
            catch
            {
                //MessageBox.Show("Error");
                return source;
            }
        }

        public static string ExtractBreadContent(string getResults)
        {
            // extract the daily bread html
            StringBuilder localContent = new StringBuilder(getResults);
            int startIndex, endIndex;

            // strip title
            startIndex = getResults.IndexOf("<div class=\"devotitle");
            endIndex = getResults.IndexOf("</div>", startIndex) + 5;
            int removedLength = endIndex - startIndex + 1;
            localContent.Remove(startIndex, endIndex - startIndex + 1);

            // strip image ref
            startIndex = getResults.IndexOf("<a href=\"/index.html\">");
            endIndex = getResults.IndexOf("</a>", startIndex) + 3;
            removedLength = removedLength + endIndex - startIndex + 1;
            localContent.Remove(startIndex, endIndex - startIndex + 1);

            startIndex = getResults.IndexOf("<div id=\"article-passage\">", endIndex);
            endIndex = getResults.IndexOf("</div>", startIndex) + 5;
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;

            // remove href for reference verse
            startIndex = getResults.IndexOf("href", endIndex);
            endIndex = getResults.IndexOf(">", startIndex) - 1;
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;
            startIndex = getResults.IndexOf("</a>", endIndex);
            localContent.Remove(startIndex - removedLength, 4);
            removedLength += 4;


            // remove href for article author
            startIndex = getResults.IndexOf("<a href", endIndex);
            endIndex = getResults.IndexOf(">", startIndex);
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;
            startIndex = getResults.IndexOf("</a>", endIndex);
            localContent.Remove(startIndex - removedLength, 4);
            removedLength += 4;

            startIndex = getResults.IndexOf("<div id=\"bible-in-a-year\">", endIndex);
            endIndex = getResults.IndexOf("</p>", startIndex) + 3;
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;

            // remove href for copyright
            startIndex = getResults.IndexOf("<a href", endIndex);
            endIndex = getResults.IndexOf(">", startIndex);
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;
            startIndex = getResults.IndexOf("</a>", endIndex);
            localContent.Remove(startIndex - removedLength, 4);
            removedLength += 4;

            startIndex = getResults.IndexOf("<div class=\"footer\">", endIndex);
            endIndex = getResults.IndexOf("</div>", startIndex) + 5;
            localContent.Remove(startIndex - removedLength, endIndex - startIndex + 1);
            removedLength = removedLength + endIndex - startIndex + 1;

            return StripHTML(localContent.ToString());
        }

        public static string ExtractVerseContent(string refBibleResults)
        {
            StringBuilder refBibleVerse = new StringBuilder("<html><body>");
            int refStartIndex = refBibleResults.IndexOf("<span id=\"en-NKJV");
            int refEndIndex = refBibleResults.IndexOf("<div class=\"publisher-info-bottom", refStartIndex);
            refBibleVerse.Append(refBibleResults.Substring(refStartIndex, refEndIndex - refStartIndex));
            refBibleVerse.Append("</body></html>");
            refBibleResults = refBibleResults.Substring(refStartIndex, refEndIndex - refStartIndex);

            //strip the footnote reference
            refStartIndex = refBibleResults.IndexOf("<sup data-fn");
            while (refStartIndex != -1)
            {
                refEndIndex = refBibleResults.IndexOf("</sup>", refStartIndex);
                refBibleResults = refBibleResults.Remove(refStartIndex, refEndIndex - refStartIndex + 6);
                refStartIndex = refBibleResults.IndexOf("<sup data-fn");
            }

            //strip the cross reference
            refStartIndex = refBibleResults.IndexOf("<sup class='crossreference'");
            while (refStartIndex != -1)
            {
                refEndIndex = refBibleResults.IndexOf("</sup>", refStartIndex);
                refBibleResults = refBibleResults.Remove(refStartIndex, refEndIndex - refStartIndex + 6);
                refStartIndex = refBibleResults.IndexOf("<sup class='crossreference'");
            }

            return StripHTML(refBibleResults);
        }
        #endregion

    }
}
